package com.xzst.lambda;

import com.alibaba.fastjson.JSON;
import com.xzst.lambda.model.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:liukexin
 * @DATE:2019-07-05 10:33
 */
@Slf4j
public class LambdaStatistics {

    List<User> userList = new ArrayList<>();


    @Before
    public void init() {
        User user = User.builder().uid("1").name("lkx").age(26).city("松原").money(new BigDecimal("11.11")).build();
        User user1 = User.builder().uid("2").name("yc").age(25).city("松原").money(new BigDecimal("22.22")).build();
        User user2 = User.builder().uid("3").name("rjy").age(24).city("松原").money(new BigDecimal("33.33")).build();
        User user3 = User.builder().uid("4").name("wyy").age(22).city("松原").money(new BigDecimal("44.44")).build();
        User user4 = User.builder().uid("5").name("wfl").age(26).city("松原").money(new BigDecimal("55.555")).build();
        User user5 = User.builder().uid("6").name("zm").age(21).city("松原").money(new BigDecimal("66.66")).build();
        User user6 = User.builder().uid("7").name("ngh").age(18).city("松原").money(new BigDecimal("77.77")).build();
        userList.add(user);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        userList.add(user6);
    }

    @Test
    public void testMinMoneyUser() {
        userList.stream().min(Comparator.comparing(User::getMoney)).ifPresent(user -> {
            log.info(JSON.toJSONString(userList));
            log.info("工资最少人的是:" + user.getName() + "工资为:" + user.getMoney());
        });
    }


    @Test
    public void testMaxMoneyUser() {
        userList.stream().max(Comparator.comparing(User::getMoney)).ifPresent(user -> {
            log.info(JSON.toJSONString(userList));
            log.info("工资最高人的是:" + user.getName() + "工资为:" + user.getMoney());
        });
    }

    @Test
    public void testSumMoney() {
        long sumAge = userList.stream().mapToLong(User::getAge).sum();
        BigDecimal sumMonry = userList.stream().map(User::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        long count = userList.stream().count();
        log.info("年龄总和:" + sumAge);
        log.info("年龄总和:" + sumMonry);
    }

    @Test
    public void testAvgAge() {
        //四舍五入
        double avgAge = new BigDecimal(userList.stream().collect(Collectors.averagingInt(User::getAge)).doubleValue()).setScale(2, RoundingMode.HALF_UP).doubleValue();
        log.info("平均年龄:avgAge" + avgAge);
    }

    private User createUser() {
        log.info("执行createUser方法");
        return User.builder().name("default").money(new BigDecimal("1.1")).build();
    }

}
